#!/usr/bin/python
#-*-coding:utf8-*-

import urllib2, urllib, sys, traceback, base64, json
import os.path as path
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5 as pkcs1
from Crypto.PublicKey import RSA

def request(url, data, headers=None):
    params = urllib.urlencode(data)
    req = urllib2.Request(url, data=params)
    if not headers is None:
        for k,v in headers.iteritems():
            req.add_header(k, v)
    res = urllib2.urlopen(req)
    res_obj = json.loads(res.read(), encoding="utf-8")
    return res_obj


def gen_sign(app_id, msg):
    # read private key
    pem_dir = path.join(path.dirname(path.abspath(__file__)), 'pem')
    pem_path = path.join(pem_dir, app_id + '_rsa_private.pem')
    private_key = open(pem_path, 'r').read()
    rsakey = RSA.importKey(private_key)
    quote_msg = urllib.quote_plus(msg)
    signer = pkcs1.new(rsakey)
    digest = SHA.new()
    digest.update(quote_msg)
    sign = signer.sign(digest)
    signature = base64.b64encode(sign)
    result = urllib.quote_plus(signature)
    return result

def loan_request(app_id, url, data):
    try:
        biz_content = json.dumps(data)
        sign = gen_sign(app_id, biz_content)
        data = {"appId": app_id, "signType": "RSA", "bizContent": biz_content, "sign": sign}
        headers = {"Content-Type", "application/json;charset=utf-8"}

        return request(url, data, headers)
    except:
        traceback.print_exc()